package top.ffhome.util.core;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import top.ffhome.util.reflect.ReflectUtil;

/** 树工具类 */
public class TreeUtil {
	/**
	 * 生成树
	 * @param list 生成树的原始列表 需要含有id、parentId、children字段
	 * @param root 根节点，默认ID为0
	 * @return 返回根节点下的所以子节点
	 */
	public static <T> List<T> generate(List<T> list, T root) {
		if (ReflectUtil.getFieldValue(root, "id") == null) {
			ReflectUtil.setFieldValue(root, "id", 0L);
		}
		return (List<T>) generateTree(list, root);
	}

	@SuppressWarnings("unchecked")
	private static <T> List<T> generateTree(List<T> list, T root) {
		List<T> children = new ArrayList<T>();
		long id = ((Long) ReflectUtil.getFieldValue(root, "id")).longValue();
		for (Iterator<T> iterator = list.iterator(); iterator.hasNext();) {
			T m = iterator.next();
			if (((Long) ReflectUtil.getFieldValue(m, "parentId")).longValue() == id) {
				children.add(m);
				iterator.remove();
			}
		}
		for (T m : children) {
			generateTree(list, m);
		}
		ReflectUtil.setFieldValue(root, "children", children);
		return (List<T>) ReflectUtil.getFieldValue(root, "children");
	}
}
